import useAppStore from '@ide/store';
import React, { useCallback, useEffect, useState } from 'react';
import { Bubble, Button, Form, Icon, Input, message } from 'tea-component';
import { Modal } from 'tea-component/lib/modal/Modal';
import { Controller, useForm, useWatch } from 'react-hook-form';
import { getStatus, validateNewContractName } from '@ide/utils/form';
import { getTemplateContracts, newFile } from '@/api';
import templateOne from '@/assets/images/template-one.png';
import templateTwo from '@/assets/images/template-two.png';
import templateThree from '@/assets/images/template-three.png';
import templateFour from '@/assets/images/template-four.png';
import { useAppOpenEditor } from '@/hooks/useAppOpenEditor';
import { useIdeStore } from 'ide-plugin';

const templateImgMap = {
  0: templateFour,
  1: templateOne,
  2: templateTwo,
  3: templateThree,
  4: templateFour,
  EVM: templateFour,
};

const NewContractByTemplate = React.forwardRef(() => {
  const { setting,getFiles,files, newContractVisible, setNewContractVisible, setNewnewContractVisible } = useAppStore();
  const { openEditor } = useIdeStore();
  const [templateList, setTemplateList] = useState<{
    contractName:string;
    templateId: string;
  }[]>([]);
  const {
    control,
    handleSubmit,
    getValues,
    setValue,
    formState: { isValidating, isSubmitted }
  } = useForm({
    mode: 'onChange',
    defaultValues: {
      contractName: '',
      template: ''
    }
  });
  const selectTemplate = useWatch({
    control,
    name: 'template'
  });
  const submit = useCallback(() => {
    const { contractName, template } = getValues();
    const path = files[0].path;
    newFile({
      path: `${path}/${contractName}`,
      fileType: 'd',
      template
    }).then(() => {
      getFiles().then(()=>{
        openEditor({
          path: `${path}/${contractName}/main.go`
        })
      });
      setNewContractVisible(false);
      setNewnewContractVisible('');
    }).catch((e) => {
      message.error({ content: e.message });
    });
  }, [files]);
  useEffect(() => {
    getTemplateContracts({}).then(res => {
      if (res.data.length) {
        setTemplateList(res.data);
        setValue('template', res.data[0]?.templateId||'');
      }
    });
  }, []);
  return <Modal
    maskClosable
    visible={newContractVisible}
    caption="创建合约工程"
    onClose={() => {
      setNewContractVisible(false)
      setNewnewContractVisible('')
    }}
    className={`${setting.theme}_model`}
    size={600}
    maskStyle={{
      backgroundColor: 'rgba(0,0,0,0.2)'
    }}
  >
    <Modal.Body>
      <Form>
        <Controller
          control={control}
          rules={{
            validate: validateNewContractName
          }}
          name="contractName"
          render={({ field, fieldState }) => (
            <Form.Item
              status={getStatus({
                fieldState,
                isValidating,
                isSubmitted
              })}
              message={fieldState.error?.message}
              label="合约名称">
              <Input size='full' placeholder='请输入合约名称' {...field}/>
            </Form.Item>
          )}
        />
        <Controller
          control={control}
          rules={{
            required: '请选择合约模版'
          }}
          name="template"
          render={({ fieldState }) => (
            <Form.Item
              status={getStatus({
                fieldState,
                isValidating,
                isSubmitted
              })}
              message={fieldState.error?.message}
              label={
                <>
                合约模版
                  <Bubble
                  arrowPointAtCenter
                  placement="top-start"
                  content="本IDE内置了若干个合约模版，其中CMID-1为身份认证标准合约、CMEVI-1为存证标准合约、CMDFA-1为数字资产标准合约、CMNFA-1为数字藏品标准合约。"
                >
                  <Icon type="help" />
                </Bubble>
              </>
              }>
              <div className='new-template-list'>
                {
                  templateList.map((item, index) => {
                    return (< div
                      onClick={() => setValue('template', item.templateId)}
                      className={`new-template-item ${selectTemplate === item.templateId ? 'active' : ''}`}
                      key={index} >
                      <div className='new-template-item-c'>
                        <img src={(templateImgMap as any)[item.templateId]} />
                        <p className='new-template-title'>{item.contractName}</p>
                      </div>
                    </div>);
                  }
                  )
                }
              </div>
            </Form.Item>
          )}
        />
        {/*
          /* <div className='new-template-item'>
            <div className='new-template-item-c'>
              <img src={templateOne} />
              <p className='new-template-title'>Evidence-standard</p>
              <p className='new-template-disc'>Ethereum is the community-run technology powering the cryptocurrency ether (ETH)</p>
              <p className='new-template-link'>{'立即使用 >'}</p>
            </div>
          </div>
          <div className='new-template-item'>
            <div className='new-template-item-c'>
              <img src={templateOne} />
              <p className='new-template-title'>Evidence-standard</p>
              <p className='new-template-disc'>Ethereum is the community-run technology powering the cryptocurrency ether (ETH)</p>
              <p className='new-template-link'>{'立即使用 >'}</p>
            </div>
          </div>
          <div className='new-template-item'>
            <div className='new-template-item-c'>
              <img src={templateOne} />
              <p className='new-template-title'>Evidence-standard</p>
              <p className='new-template-disc'>Ethereum is the community-run technology powering the cryptocurrency ether (ETH)</p>
              <p className='new-template-link'>{'立即使用 >'}</p>
            </div>
          </div>
          <div className='new-template-item'>
            <div className='new-template-item-c'>
              <img src={templateOne} />
              <p className='new-template-title'>Evidence-standard</p>
              <p className='new-template-disc'>Ethereum is the community-run technology powering the cryptocurrency ether (ETH)</p>
              <p className='new-template-link'>{'立即使用 >'}</p>
            </div>
          </div>
        */}
      </Form>
    </Modal.Body>
    <Modal.Footer>
      <Button type="primary" onClick={handleSubmit(submit)}>
        确定
      </Button>
      <Button type="weak" onClick={() => {
        setNewContractVisible(false)
        setNewnewContractVisible('')
      }}>
        取消
      </Button>
    </Modal.Footer>
  </Modal>;
});
NewContractByTemplate.displayName = 'NewContractByTemplate';

export default NewContractByTemplate;
